package dryven.util;

import java.io.File;
import java.io.IOException;

public class ImageCache {
	
	private String _appDataPath;
	private final static String OriginalFolder = "orig";
	private final static String RootSubFolder = "photos";
	
	public ImageCache(String appDataPath) {
		_appDataPath = appDataPath;
		if(!_appDataPath.endsWith("/")) {
			_appDataPath=_appDataPath+"/";
		}
	}
	
	public String getCachedImage(int id, int width, int height, boolean cropped) {
		String cachedPath = getScaledCachePhotoPath(id, width, height, cropped);
		File cachedFile = new File(cachedPath);
		File originalFile = new File(getOriginalPhotoPath(id,_appDataPath));

		//is the cache dirty?
		boolean dirty = !cachedFile.exists();
		if(!dirty) {
			dirty = cachedFile.lastModified()<originalFile.lastModified();
		}
		if(dirty) {
			File dir = cachedFile.getParentFile();
			if(!dir.exists()) {
				dir.mkdirs();
			}
			if(!originalFile.canRead()) {
				throw new RuntimeException("Can't read image with id "+id);
			}
			ImageScaler scaler = new ImageScaler(originalFile.getAbsolutePath());
			try {
				if(cropped) {
					scaler.scaleCropped(width, height, cachedPath);
				} else {
					scaler.scaleProportional(width, height, cachedPath);
				}
			} catch(IOException e) {
				throw new RuntimeException("Could not write scaled image", e);
			}
		}
		return cachedPath;
	}
	
	public static String getOriginalPhotoPath(int id, String appDataPath) {
		return appDataPath+RootSubFolder+File.separator+OriginalFolder+File.separator+id+".jpg";
	}
	
	public String getScaledCachePhotoPath(int id, int width, int height, boolean cropped) {
		String croppedPathPart = "";
		if(cropped) {
			croppedPathPart = "-cropped";
		}
		return _appDataPath+RootSubFolder+File.separator+width+"x"+height+croppedPathPart+File.separator+id+".png";
	}
}
